//
//  CZEmoticonBottomView.swift
//  CZVVeiBo
//
//  Created by smile on 2017/8/6.
//  Copyright © 2017年 itcast. All rights reserved.
//

import UIKit
// 按钮枚举
enum CZEmoticonBottomViewType:Int {
    case normal = 2001
    case emoji = 2002
    case lxh = 2003
}

class CZEmoticonBottomView: UIView {
    
    // 闭包
    var closure:((CZEmoticonBottomViewType)->())?
    
    // 记录选中的按钮
    var selectedButton: UIButton?

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 设置视图
    private func setupUI(){
        let normalButton = addChildButtons(imgName: "left", tilte: "默认", type: .normal)
        let emojiButton = addChildButtons(imgName: "mid", tilte: "Emoji", type: .emoji)
        let lxhButton = addChildButtons(imgName: "right", tilte: "浪小花", type: .lxh)
        
        normalButton.snp.makeConstraints { (make) in
            make.top.bottom.left.equalTo(self)
            make.width.equalTo(emojiButton)
        }
        
        emojiButton.snp.makeConstraints { (make) in
            make.top.bottom.equalTo(self)
            make.width.equalTo(lxhButton)
            make.left.equalTo(normalButton.snp.right)
        }
        
        lxhButton.snp.makeConstraints { (make) in
            make.top.bottom.right.equalTo(self)
            make.left.equalTo(emojiButton.snp.right)
        }
        
    }
    // MARK: - 创建按钮
    func addChildButtons(imgName: String, tilte:String, type: CZEmoticonBottomViewType) -> UIButton{
        let button = UIButton()
        // 如果是type == .normal 设置为选中状态
        if type == .normal {
            button.isSelected = true
            selectedButton = button
        }
        // 设置tag
        button.tag = type.rawValue
        button.addTarget(self, action: #selector(buttonClick), for: UIControlEvents.touchUpInside)
        button.setBackgroundImage(UIImage(named: "compose_emotion_table_\(imgName)_normal"), for: UIControlState.normal)
        button.setBackgroundImage(UIImage(named: "compose_emotion_table_\(imgName)_selected"), for: UIControlState.selected)
        button.setTitle(tilte, for: UIControlState.normal)
        button.setTitleColor(UIColor.white, for: UIControlState.normal)
        button.setTitleColor(UIColor.darkGray, for: UIControlState.selected)
        button.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        addSubview(button)
        return button
    }
    
    @objc private func buttonClick(button: UIButton){
        
        // 如果当前按钮已经选中
        if selectedButton == button {
            return
        }
        
        // 取消选中的按妞的选中状态
        selectedButton?.isSelected = false
        button.isSelected = true
        selectedButton = button
        
        // 执行闭包
        closure?(CZEmoticonBottomViewType(rawValue: button.tag)!)
    }
}
